package com.yang.common.util;

import cn.hutool.core.util.StrUtil;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

/**
 * 通用格式化工具
 *
 * @author: yangjianzhi
 * @version1.0
 */
public class CommonFormatUtil {

    /**
     * 将文件大小转换为合适的单位
     * size: byte
     */
    public static String formatFileSize(long size) {
        if (size <= 0) {
            return "0 B";
        }

        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));

        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    /**
     * 格式化时间字符串，尽可能匹配所有的字符串
     */
    public static String formatDateTime(String timeString) {
        if (StrUtil.isBlank(timeString)) {
            return timeString;
        }
        // 格式处理
        timeString = timeString.replaceAll("：", ":");
        timeString = timeString.toUpperCase();
        timeString = timeString.replaceAll("\\s{2,}", " ");

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        List<DateTimeFormatter> inputFormatters = new ArrayList<>();
        inputFormatters.add(DateTimeFormatter.ofPattern("yyyy年M月d日"));
        // 拓展
        List<String> ymdList = Arrays.asList("yyyy年M月d日", "yyyy年MM月dd日", "yyyy/MM/dd", "yyyy/M/d", "yyyy-MM-dd", "yyyy-M-d");
        List<String> hmsList = Arrays.asList(" HH:mm:ss", " H:m:s", " HH:mm", " H:m", "HH时mm分ss秒", "H时m分s秒", "HH时mm分", "H时m分", "HH时", "H时"
                , " hh:mm:ssa", " h:m:sa", " hh:mma", " h:ma", " hh:mm:ss a", " h:m:s a", " hh:mm a", " h:m a");
        for (String ymd : ymdList) {
            for (String hms : hmsList) {
                inputFormatters.add(DateTimeFormatter.ofPattern(ymd + hms, Locale.ENGLISH));
            }
        }

        // 匹配解析
        for (DateTimeFormatter inputFormatter : inputFormatters) {
            try {
                LocalDateTime parsedDateTime = LocalDateTime.parse(timeString, inputFormatter);
                return parsedDateTime.format(outputFormatter);
            } catch (Exception e) {
                // 如果解析失败，继续尝试下一个格式
            }
        }

        // 都不匹配则返回原来字符串
        return timeString;
    }
}
